package reptile;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 */
public class ExportExcelUtil {

    /**
     * 创建Excel对象
     */
    public static void ExportExcel(LinkedHashMap<String, String> header, List<Map<String, Object>> body, String savePath) {
        Workbook workbook;
        workbook = new XSSFWorkbook();// 创建一个 2007 excel文档对象
        Sheet sheet = workbook.createSheet();// 创建一个工作薄对象
        Row row = sheet.createRow(0);// 创建一个行对象,从0行开始

        // 设置表头
        for (Map.Entry head : header.entrySet()) {
            createCell(row).setCellValue(head.getValue() + "");
            int columnIndex = row.getLastCellNum() - 1;
            sheet.setColumnWidth(columnIndex, getColumnWidth(head.getValue() + ""));
        }

        // 设置表体
        for (Map rowMap : body) {
            row = createRow(sheet);
            for (Map.Entry head : header.entrySet()) {
                //固定字符串格式
                //createCell(row).setCellValue(rowMap.get(head.getKey()) == null ? "" : rowMap.get(head.getKey()) + "");
                //动态格式
                dynamicCreateCell(row, rowMap.get(head.getKey()));
            }
        }

        OutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(savePath);
            workbook.write(fileOut);
            System.out.println("Excel路径:" + savePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOut != null)
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }


    //创建行
    private static Row createRow(Sheet sheet) {
        return sheet.createRow(sheet.getLastRowNum() + 1);
    }

    //创建列单元格
    private static Cell createCell(Row row) {
        int columnIndex = row.getLastCellNum();
        if (columnIndex < 0) {
            return row.createCell(columnIndex + 1);
        } else {
            return row.createCell(columnIndex);
        }
    }

    //获取列头内容宽度
    private static int getColumnWidth(String str) {
        try {
            double len = new String(str.getBytes("GBK"), "ISO8859_1").length();
            return new Double(len * 1.2 * 256).intValue();
        } catch (UnsupportedEncodingException e) {
            return str.length();
        }
    }

    //根据数据类型动态创建单元格
    private static void dynamicCreateCell(Row row, Object val) {
        int t = row.getLastCellNum();
        Cell cell;
        if (t < 0) {
            cell = row.createCell(t + 1);
        } else {
            cell = row.createCell(t);
        }
        if (val instanceof Integer) {
            int value = (Integer) val;
            cell.setCellValue(value);
        } else if (val instanceof String) {
            String s = (String) val;
            cell.setCellValue(s);
        } else if (val instanceof Double) {
            double d = (Double) val;
            cell.setCellValue(d);
        } else if (val instanceof Float) {
            float f = (Float) val;
            cell.setCellValue(f);
        } else if (val instanceof Long) {
            long l = (Long) val;
            cell.setCellValue(l);
        } else if (val instanceof Boolean) {
            boolean b = (Boolean) val;
            cell.setCellValue(b);
        } else if (val instanceof Date) {
            Date d = (Date) val;
            cell.setCellValue(d);
        } else if (val instanceof BigDecimal) {
            cell.setCellValue(new BigDecimal(val + "").doubleValue());
        }
    }
}